package com.webber.demo;


import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * 
 * <p>Title: UploadServlet.java</p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2017</p>
 * <p>ProjectName: uploadFile</p>
 * @Package com.webber.demo 
 * @author JobsZhang
 * @date 2017年10月19日 上午9:42:13
 * @version uploadFile 1.0
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String serverPath = "E:/test/uploadFile";
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    	File f =  new File(serverPath);
		if(!f.exists()) {
			f.mkdirs();
		}
        //1.配置缓存
        DiskFileItemFactory factory = new DiskFileItemFactory(1*1024*1024,new File(serverPath));
        //2.创建ServleFileUpload对象
        ServletFileUpload sfu = new ServletFileUpload(factory);
        //解决文件名称中文问题
        sfu.setHeaderEncoding("utf-8");
        //3.解析
        try {
            List<FileItem> list = sfu.parseRequest(request);
            //解析所有内容
            if(list!=null){
                for(FileItem item:list){
                    //判断是否为普通表单参数
                    if(item.isFormField()){
                        //普通表单参数
                        //获取表单的name属性名称
                        String fieldName = item.getFieldName();
                        //获取表单参数值
                        String value = item.getString("utf-8");
                    }else{
                        //文件
                        if(item.getName()!=null && !item.getName().equals(""))  {
                            //保存到服务器硬盘                  
                            try {
								item.write(new File(serverPath+item.getName()));
							} catch (Exception e) {
								e.printStackTrace();
							}
                            item.delete();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        doGet(request, response);
    }

}
